Checking condition while Exception handling in python
Checking condition while Exception handling in python
242
20-Jul-2023
Updated on 20-Jul-2023
Aryan Kumar
20-Jul-2023Sure, here is how you can check a condition while exception handling in Python:
Python
In this example, the function
my_function()tries to divide 1 by 0. If this division is successful, thetryblock will be executed. However, if the division fails, aZeroDivisionErrorexception will be raised and theexceptblock will be executed.In the
exceptblock, we check if the number is even. If the number is even, we print the message "The number is even." Otherwise, we print the message "The number is odd."Here is another example:
Python
In this example, the function
my_function()asks the user to enter a number. Thetryblock tries to convert the user input to an integer. If the conversion is successful, thetryblock will be executed. However, if the conversion fails, aValueErrorexception will be raised and theexceptblock will be executed.In the
exceptblock, we print the message "Invalid input. Please enter a valid number." Otherwise, we check if the number is greater than 10. If the number is greater than 10, we print the message "The number is greater than 10." Otherwise, we print the message “The number is less than or equal to 10.”